package com.ys.erp.stage_user_service.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.entity.data.bean.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 幺豆充值通知工具类
 * @author zjj
 * @date 2025/06/30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PulseNotificationUtil {

    @Value("${properties.wx.mini-program-state:formal}")
    private String miniProgramState;

    @Value("${properties.wx.pulse-recharge-template-id:}")
    private String pulseRechargeTemplateId;

    private final WxUtil wxUtil;

    private final RestTemplate restTemplate;

    /**
     * 发送幺豆充值通知
     *
     * @param user          用户信息
     * @param rechargeAmount 充值金额
     * @param currentBalance 当前余额
     * @param operatorName  操作员姓名
     * @param remark        备注
     */
    @Async
    public void sendPulseRechargeNotification(User user, String rechargeAmount, Long currentBalance, String operatorName, String remark) {
        try {
            if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getOpenId())) {
                log.warn("用户信息或openId为空，无法发送幺豆充值通知，用户ID：{}", user != null ? user.getId() : "null");
                return;
            }

            if (ObjectUtils.isEmpty(pulseRechargeTemplateId)) {
                log.warn("幺豆充值通知模板ID未配置，无法发送通知");
                return;
            }

            JSONObject dataObj = new JSONObject();
            
            // 充值金额
            JSONObject amountObj = new JSONObject();
            amountObj.put("value", rechargeAmount + "元");
            dataObj.put("amount1", amountObj);
            
            // 当前余额
            JSONObject balanceObj = new JSONObject();
            balanceObj.put("value", formatMoney(currentBalance));
            dataObj.put("amount2", balanceObj);
            
            // 充值时间
            JSONObject timeObj = new JSONObject();
            timeObj.put("value", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            dataObj.put("time3", timeObj);
            
            // 操作员
            JSONObject operatorObj = new JSONObject();
            operatorObj.put("value", ObjectUtils.isNotEmpty(operatorName) ? operatorName : "系统");
            dataObj.put("name4", operatorObj);
            
            // 备注信息
            JSONObject remarkObj = new JSONObject();
            String remarkText = ObjectUtils.isNotEmpty(remark) ? remark : "幺豆充值成功";
            if (remarkText.length() > 20) {
                remarkText = remarkText.substring(0, 19) + "...";
            }
            remarkObj.put("value", remarkText);
            dataObj.put("thing5", remarkObj);

            sendMessage(user.getOpenId(), pulseRechargeTemplateId, "pages/user/pulse/index", dataObj);
            
            log.info("幺豆充值通知发送成功，用户ID：{}，充值金额：{}", user.getId(), rechargeAmount);
            
        } catch (Exception e) {
            log.error("发送幺豆充值通知失败，用户ID：{}，充值金额：{}", user != null ? user.getId() : "null", rechargeAmount, e);
        }
    }

    /**
     * 格式化金额显示
     *
     * @param amount 金额（分）
     * @return 格式化后的金额字符串
     */
    private String formatMoney(Long amount) {
        if (amount == null) {
            return "0.00元";
        }
        double yuan = amount / 100.0;
        return String.format("%.2f元", yuan);
    }

    /**
     * 发送微信订阅消息
     *
     * @param openId      用户openId
     * @param templateId  模板ID
     * @param page        跳转页面
     * @param data        消息数据
     */
    private void sendMessage(String openId, String templateId, String page, JSONObject data) {
        try {
            String accessToken = wxUtil.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
            
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            
            JSONObject param = new JSONObject();
            param.put("template_id", templateId);
            param.put("page", page);
            param.put("touser", openId);
            param.put("data", data);
            param.put("miniprogram_state", miniProgramState);
            param.put("lang", "zh_CN");
            
            HttpEntity<String> entity = new HttpEntity<>(param.toJSONString(), headers);
            String response = restTemplate.postForObject(url, entity, String.class);
            
            log.info("发送幺豆充值通知参数：{}", param.toString());
            log.info("发送幺豆充值通知结果：{}", response);
            
        } catch (Exception e) {
            log.error("发送微信订阅消息失败", e);
        }
    }
} 